package com.uzai.console.service.jd.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.uzai.common.enums.OrderReStatusEnum;
import com.uzai.common.enums.OrderStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.feign.jdorder.JdOrderDownloadDto;
import com.uzai.console.dto.feign.jdorder.JdOrderSettledDto;
import com.uzai.console.dto.jd.jdorder.JdFindUnReceicedDto;
import com.uzai.console.dto.jd.jdorder.JdOrderApiDownLoadDto;
import com.uzai.console.dto.jd.jdorder.JdOrderDownLoadDto;
import com.uzai.console.dto.feign.jdorder.JdOrderPullDto;
import com.uzai.console.dto.tb.tborder.TbFindUnReceicedDto;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.entity.JdOrder;
import com.uzai.console.entity.JdToken;
import com.uzai.console.entity.JdTokenApi;
import com.uzai.console.entity.TbOrder;
import com.uzai.console.mapper.JdOrderMapper;
import com.uzai.console.mapper.JdTokenApiMapper;
import com.uzai.console.mapper.JdTokenMapper;
import com.uzai.console.para.JdOrderRemoteApiPara;
import com.uzai.console.service.feign.JdOrderFeignService;
import com.uzai.console.service.jd.JdOrderSyncService;
import com.uzai.console.service.remoteapi.JdOrderRemoteApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: liuqi
 * @Date: 2019/11/27 11:23
 * @Description:
 */
@Service
public class JdOrderSyncServiceImpl implements JdOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(JdOrderSyncServiceImpl.class);

    @Autowired
    private JdTokenMapper jdTokenMapper;
    @Autowired
    private JdOrderMapper jdOrderMapper;
    @Autowired
    private JdOrderRemoteApiService jdOrderRemoteApiService;
    @Autowired
    private JdOrderFeignService jdOrderFeignService;
    @Autowired
    private JdTokenApiMapper jdTokenApiMapper;

    /**
     * 手动下载单个京东联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrder(JdOrderDownLoadDto jdOrderDownLoadDto, Long jdTokenId) {

        //调用订单业务库服务器
        JdToken jdToken = jdTokenMapper.selectById(jdTokenId, jdOrderDownLoadDto.getMerId());
        if (jdToken != null) {
            try{
                JdOrderPullDto jdOrderPullDto = new JdOrderPullDto();
                jdOrderPullDto.setTokenId(jdToken.getUnionId());
                jdOrderPullDto.setPlatform("jd");
                jdOrderPullDto.setStartTime(jdOrderDownLoadDto.getQueryStartTime());
                jdOrderPullDto.setEndTime(jdOrderDownLoadDto.getQueryEndTime());
                //时间类型 0订单库入库时间， 1订单库更新时间， 2订单创建时间， 3订单最后更新时间， 4订单付款时间， 5订单完成（收货）时间， 6订单结算时间，7订单维权创建时间，8订单维权完成时间")
                Integer timeType = 2;
                if(jdOrderDownLoadDto.getQueryTimeType() == 1){ //订单下单时间
                    timeType = 2;
                }else if(jdOrderDownLoadDto.getQueryTimeType() == 2){ //订单完成时间
                    timeType = 5;
                }else if(jdOrderDownLoadDto.getQueryTimeType() == 3){ //订单更新时间
                    timeType = 1;
                }
                jdOrderPullDto.setTimeType(timeType);
                //请求订单拉取接口
                jdOrderFeignService.pull(jdOrderPullDto);
            }catch (Exception e){
                logger.error(e.getMessage());
            }
        }


        if (jdToken != null) {
            //调用订单拉取库服务器
            JdOrderRemoteApiPara jdOrderRemoteApiPara = new JdOrderRemoteApiPara();
            jdOrderRemoteApiPara.setQueryTimeType(jdOrderDownLoadDto.getQueryTimeType());
            jdOrderRemoteApiPara.setQueryStartTime(jdOrderDownLoadDto.getQueryStartTime());
            jdOrderRemoteApiPara.setQueryEndTime(jdOrderDownLoadDto.getQueryEndTime());
            jdOrderRemoteApiService.remoteDownload(jdOrderRemoteApiPara);
        }
    }

    /**
     * 通过API手动下载单个京东联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderApiDownLoadDto
     * @return null
     */
    @Override
    public void downloadOrderApi(JdOrderApiDownLoadDto jdOrderApiDownLoadDto, Long jdTokenId) {
        //调用订单业务库服务器
        JdTokenApi jdTokenApi = jdTokenApiMapper.selectById(jdTokenId, jdOrderApiDownLoadDto.getMerId());
        if (jdTokenApi != null) {
            List<TimeVO> jdOrderTimeScope = DateUtil.getJdOrderTimeScope_ByAppKey(jdOrderApiDownLoadDto.getQueryStartTime(), jdOrderApiDownLoadDto.getQueryEndTime());
            //对象转成JSON字符串，保存到redis队列中
            //往redis队列中塞阿里妈妈tokens
            if(jdOrderTimeScope != null && jdOrderTimeScope.size() > 0) {
                for (TimeVO timeVO : jdOrderTimeScope) {
                    JdOrderDownloadDto jdOrderDownloadDto = new JdOrderDownloadDto();
                    jdOrderDownloadDto.setAuthKey(jdTokenApi.getAuthKey());
                    jdOrderDownloadDto.setBeginTime(timeVO.getBeginTime());
                    jdOrderDownloadDto.setEndTime(timeVO.getEndTime());
                    jdOrderDownloadDto.setQueryType(jdOrderApiDownLoadDto.getQueryTimeType());
                    //请求订单拉取接口
                    UzaiRespVo<Boolean> uzaiRespVo = jdOrderFeignService.jdOrderDownload(jdOrderDownloadDto);
                    logger.info("--手动通过API拉取京东订单-para={},result={}", JSONObject.toJSONString(jdOrderDownloadDto),JSONObject.toJSONString(uzaiRespVo));
                }
            }
        }
    }

    /**
     * 异步手动下载多个京东联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderDownLoadDto
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void downloadOrderListSync(JdOrderDownLoadDto jdOrderDownLoadDto) {
        if(jdOrderDownLoadDto.getIdList() != null && jdOrderDownLoadDto.getIdList().size() > 0){
            for (Long id : jdOrderDownLoadDto.getIdList()){
                try {
                    downloadOrder(jdOrderDownLoadDto, id);
                }catch (Exception e){
                    logger.error("-------downloadOrderListSync is error jdTokenId={}, error={}", id, e.getMessage());
                }
            }
        }
    }

    /**
     * 通过API手动下载所有单个京东联盟订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrderApiDownLoadDto
     * @return null
     */
    //@Async("taskExecutor")
    @Override
    public void downloadOrderApiListSync(JdOrderApiDownLoadDto jdOrderApiDownLoadDto){
        if(jdOrderApiDownLoadDto.getIdList() != null && jdOrderApiDownLoadDto.getIdList().size() > 0){
            for (Long id : jdOrderApiDownLoadDto.getIdList()){
                try {
                    downloadOrderApi(jdOrderApiDownLoadDto, id);
                }catch (Exception e){
                    logger.error("-------downloadOrderApiListSync is error jdTokenId={}, error={}", id, e.getMessage());
                }
            }
        }
    }


    /**
     * 远程调用订单库API，手动更新单个订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param jdOrder
     * @return null
     */
    @Async("taskExecutor")
    @Override
    public void updateJdOrder(JdOrder jdOrder) {
        //调用订单拉取库服务器
        JdOrderRemoteApiPara jdOrderRemoteApiPara = new JdOrderRemoteApiPara();
        jdOrderRemoteApiPara.setQueryTimeType(1); //下单时间
        jdOrderRemoteApiPara.setQueryStartTime(jdOrder.getCreatedt() - 1);
        jdOrderRemoteApiPara.setQueryEndTime(jdOrder.getCreatedt() + 1);
        jdOrderRemoteApiPara.setChildOrderNo(jdOrder.getChildOrderNo());
        jdOrderRemoteApiService.remoteDownload(jdOrderRemoteApiPara);

    }

    @Override
    public void uploadJdOrderSettingSync(Long merId, int day, int status, List<Integer> sourceStatus) {
        if (merId == null) {
            return;
        }
        //设置结束时间为day天前
        int endTime = DateUtil.getNowTime() - day * 24 * 3600;
        jdOrderMapper.updateStatusPayCompleteToSettle(null, endTime, null, merId, status, sourceStatus);
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    @Override
    public void updateJdOrderUnReceivedListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        jdFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        jdFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        jdFindUnReceicedDto.setStatus(0);
        List<JdOrder> jdOrderList =  jdOrderMapper.findUnReceivedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    updateJdOrder(jdOrder);
                }catch (Exception e){
                    logger.error("-------updateJdOrderUnReceivedListSync is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    @Override
    public void updateJdOrderFreezedListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        jdFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        jdFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（已收货）
        jdFindUnReceicedDto.setStatus(1);
        List<JdOrder> jdOrderList =  jdOrderMapper.findFreezedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    updateJdOrder(jdOrder);
                }catch (Exception e){
                    logger.error("-------updateJdOrderFreezedListSync is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    @Override
    public void updateJdOrderUnReceivedListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        jdFindUnReceicedDto.setQueryStartTime(startTime);
        jdFindUnReceicedDto.setQueryEndTime(endTime);
        jdFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        jdFindUnReceicedDto.setStatus(0);
        List<JdOrder> jdOrderList =  jdOrderMapper.findUnReceivedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    updateJdOrder(jdOrder);
                }catch (Exception e){
                    logger.error("-------updateJdOrderUnReceivedListSync is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单,直接结算
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    @Override
    public void updateJdOrderUnReceivedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        jdFindUnReceicedDto.setQueryStartTime(startTime);
        jdFindUnReceicedDto.setQueryEndTime(endTime);
        jdFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        jdFindUnReceicedDto.setStatus(0);
        List<JdOrder> jdOrderList =  jdOrderMapper.findUnReceivedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    //订单状态为0-付款状态时，才能确认收货
                    if(jdOrder.getStatus() == 0){
                        //调用确认收货接口
                        JdOrderSettledDto jdOrderSettledDto = new JdOrderSettledDto();
                        jdOrderSettledDto.setMerId(jdOrder.getMerId());
                        jdOrderSettledDto.setOrderId(jdOrder.getParentOrderNo());
                        jdOrderSettledDto.setChildOrderId(jdOrder.getChildOrderNo());
                        UzaiRespVo<Object> result =  jdOrderFeignService.settled(jdOrderSettledDto);
                        logger.info("---京东订单确认收货---dto={}, result={}" ,JSONObject.toJSONString(jdOrderSettledDto), JSONObject.toJSONString(result));
                        if(result.getCode() != 200){
                            throw  new BusinessException(result.getCode(), result.getMsg());
                        }
                    }
                }catch (Exception e){
                    logger.error("-------updateJdOrderUnReceivedListSync_settle is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }


    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    public void updateJdOrderFreezedListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        jdFindUnReceicedDto.setQueryStartTime(startTime);
        jdFindUnReceicedDto.setQueryEndTime(endTime);
        jdFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        jdFindUnReceicedDto.setStatus(1);
        List<JdOrder> jdOrderList =  jdOrderMapper.findFreezedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    updateJdOrder(jdOrder);
                }catch (Exception e){
                    logger.error("-------updateJdOrderFreezedListSync is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前已冻结订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    public void updateJdOrderFreezedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId){
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        jdFindUnReceicedDto.setQueryStartTime(startTime);
        jdFindUnReceicedDto.setQueryEndTime(endTime);
        jdFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        jdFindUnReceicedDto.setStatus(1);
        List<JdOrder> jdOrderList =  jdOrderMapper.findFreezedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    //先将订单状态修改为0-付款状态时，才能确认收货
                    jdOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    jdOrderMapper.updateStatus(jdOrder);
                    //调用确认收货接口
                    JdOrderSettledDto jdOrderSettledDto = new JdOrderSettledDto();
                    jdOrderSettledDto.setMerId(jdOrder.getMerId());
                    jdOrderSettledDto.setOrderId(jdOrder.getParentOrderNo());
                    jdOrderSettledDto.setChildOrderId(jdOrder.getChildOrderNo());
                    UzaiRespVo<Object> result =  jdOrderFeignService.settled(jdOrderSettledDto);
                    logger.info("---京东订单确认收货---dto={}, result={}" ,JSONObject.toJSONString(jdOrderSettledDto), JSONObject.toJSONString(result));
                    if(result.getCode() != 200){
                        throw  new BusinessException(result.getCode(), result.getMsg());
                    }
                }catch (Exception e){
                    logger.error("-------updateJdOrderFreezedListSync_settle is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }


    /**
     * 远程调用订单库API，更新day天前未收货订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param day
     * @return null
     */
    @Override
    public void updateJdOrderRefundingListSync(Long merId, int day) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        jdFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        jdFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        jdFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<JdOrder> jdOrderList =  jdOrderMapper.findUnReceivedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    updateJdOrder(jdOrder);
                }catch (Exception e){
                    logger.error("-------updateJdOrderRefundingListSync is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }


    /**
     * 远程调用订单库API，更新day天前维权中订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    @Override
    public void updateJdOrderRefundingListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        jdFindUnReceicedDto.setQueryStartTime(startTime);
        jdFindUnReceicedDto.setQueryEndTime(endTime);
        jdFindUnReceicedDto.setUserId(userId);
        //查询维权中状态订单
        jdFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<JdOrder> jdOrderList =  jdOrderMapper.findUnReceivedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    updateJdOrder(jdOrder);
                }catch (Exception e){
                    logger.error("-------updateJdOrderRefundingListSync is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前维权中订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @param startTime
     * @return null
     */
    public void updateJdOrderRefundingListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId){
        if(merId == null){
            return;
        }
        //查询7天前未收货订单
        JdFindUnReceicedDto jdFindUnReceicedDto = new JdFindUnReceicedDto();
        jdFindUnReceicedDto.setMerId(merId);
        jdFindUnReceicedDto.setQueryStartTime(startTime);
        jdFindUnReceicedDto.setQueryEndTime(endTime);
        jdFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（维权中）
        jdFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        //根据订单返利状态查询
        jdFindUnReceicedDto.setReStatusList(Lists.newArrayList(OrderReStatusEnum.RE_STATUS_NO_VALUE, OrderReStatusEnum.RE_STATUS_FROZEN_VALUE));
        List<JdOrder> jdOrderList =  jdOrderMapper.findUnReceivedList(jdFindUnReceicedDto);
        if(jdOrderList != null){
            for (JdOrder jdOrder : jdOrderList){
                try {
                    //先将订单状态修改为0-付款状态时，才能确认收货
                    jdOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    jdOrderMapper.updateStatus(jdOrder);
                    //调用确认收货接口
                    JdOrderSettledDto jdOrderSettledDto = new JdOrderSettledDto();
                    jdOrderSettledDto.setMerId(jdOrder.getMerId());
                    jdOrderSettledDto.setOrderId(jdOrder.getParentOrderNo());
                    jdOrderSettledDto.setChildOrderId(jdOrder.getChildOrderNo());
                    UzaiRespVo<Object> result =  jdOrderFeignService.settled(jdOrderSettledDto);
                    logger.info("---京东订单确认收货---dto={}, result={}" ,JSONObject.toJSONString(jdOrderSettledDto), JSONObject.toJSONString(result));
                    if(result.getCode() != 200){
                        throw  new BusinessException(result.getCode(), result.getMsg());
                    }
                }catch (Exception e){
                    logger.error("-------updateJdOrderRefundindListSync_settle is error ordersn={}, error={}", jdOrder.getParentOrderNo(),e.getMessage());
                    continue;
                }
            }
        }
    }

}
